package two.chapter_1.c1_3;

import java.util.Iterator;

public  class Bag<Item> implements Collection<Item> {

    public Item[] items;
    private static final int DEFAULT_CAPACITY=10;
    private int size;
    public Bag(){
        items= (Item[]) new Object[DEFAULT_CAPACITY];
    }

    public void add(Item item){
        ensureCapacity();
        items[size++]=item;
    }

    private void ensureCapacity() {
        int N=items.length;
        if (size>=N){
            int newLength= (int) (N+0.5*N);
            resize(newLength);
        }

    }

    private void resize(int newLength) {
        Item[] newItems= (Item[]) new Object[newLength];
        System.arraycopy(items,0,newItems,0,items.length);
        items=newItems;
    }


    @Override
    public boolean isEmpty() {
        return size()==0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Iter();
    }

    private class Iter implements Iterator<Item>{

        private int position;
        @Override
        public boolean hasNext() {
            return position+1<=size();
        }

        @Override
        public Item next() {
            return items[position++];

        }

        @Override
        public void remove() {

        }
    }
}
